<template>
     <div><h2>客房列表</h2></div>
     <div>
      <el-form :inline="true">
        <el-form-item>
            <el-button type="primary" @click="dialogFormVisible = true">添加客房</el-button>
            <el-button type="success" @click="handleDels">删除客房</el-button>
            
            <el-upload
              action="http://localhost:8082/lxhotel/roomServlet.do?oper=impt"
              :show-file-list="false"
              :on-success="handleImportRoomSuccess"
              :before-upload="beforeAvatarUpload">
              <el-button type="info"  >导入数据</el-button>
            </el-upload>


            <!-- <el-button type="warning" @click="handleExprot">导出数据</el-button> -->
            <!-- http://localhost:8082/lxhotel/roomServlet.do?oper=expt -->
           <!-- <el-link href="http://localhost:8082/lxhotel/roomServlet.do?oper=expt" >
              <el-button type="warning" >导出数据</el-button>
           </el-link> -->
           <el-button type="warning" tag="a"  href="http://localhost:8082/lxhotel/roomServlet.do?oper=expt" >导出数据</el-button>
        </el-form-item>
          <el-form-item label="房号">
             <el-input  v-model="queryForm.rnmb" placeholder="房号" clearable />
          </el-form-item>
          <el-form-item label="价格">
             <el-input   v-model="queryForm.price"  placeholder="价格" clearable />
          </el-form-item>

          <el-form-item label="类型">
             <el-select v-model="queryForm.rtype" placeholder="选择客房类型"  clearable>
                <el-option label="标准间" value="1" />
                <el-option label="大床房" value="2" />
                <el-option label="三人间" value="3" />
              </el-select>
           </el-form-item>
           <el-form-item>
             <el-button type="primary" @click="handleQuery">查询</el-button>
           </el-form-item>
        </el-form>
     </div>
    <el-table :data="tableData" stripe  border  style="width: 100%" ref="multipleTableRef">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="roomid" label="ID" width="180" />
      <el-table-column  label="封面" width="180" >
          <template #default="scope"> 
                <el-image :src="scope.row.rpic" class="rpic"  :preview-src-list="scope.row.rpic"  >
                  <template #error>
                    <div class="image-slot">
                      <!-- <img src="http://localhost:8082/lxfiles/jdfm5.jpg" class="rpic" /> -->
                      <el-image :src="'http://localhost:8082/lxfiles/jdfm5.jpg'" class="rpic"   :preview-src-list="['http://localhost:8082/lxfiles/jdfm5.jpg']"  />
                    </div>
                  </template>
                </el-image>
         </template>
      </el-table-column>
      <el-table-column prop="rnmb" label="房号" width="180" />
      <el-table-column  label="类型" >
         <template #default="scope"> 
               <div v-if="scope.row.rtype == 1">标准间</div>
               <div v-if="scope.row.rtype == 2">大床房</div>
               <div v-if="scope.row.rtype == 3">三人间</div>
               <div v-if="scope.row.rtype == 4">总统套房</div>
         </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" width="180" />
      <el-table-column prop="ydstate" label="预定状态" />
      <el-table-column  label="使用状态" width="180" >
        <template #default="scope"> 
          <el-tag class="ml-2" type="success" effect="dark" v-if="scope.row.ustate == 1">未入住</el-tag>
          <el-tag class="ml-2" type="warning" effect="dark" v-if="scope.row.ustate == 2">维护中</el-tag>
          <el-tag class="ml-2" type="danger"  effect="dark" v-if="scope.row.ustate == 3">已入住</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
           <el-button link type="danger" size="small"  @click="handleDel(scope.$index)">删除</el-button>
           <el-button link type="primary" size="small" @click="handleUpdate(scope.$index)">更新</el-button>
        </template>
      </el-table-column>
    </el-table>
 <!-- 分页 -->
 <div>
      <el-pagination
        v-model:current-page="pageObj.currentPage"
        v-model:page-size="pageObj.pageSize"
        :page-sizes="[5, 10, 20, 25]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageObj.totalRow"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
   </div>
<!-- ./分页 -->



    <!-- 添加框 --> 
    <el-dialog v-model="dialogFormVisible"   z-index="2" :title="form.roomid==''?'添加客房信息':'修改客房信息'"  @close="handleClose(formRef)">
      <el-form :model="form" ref="formRef"  :rules="rules" >
        <el-form-item label="房号"    prop="rnmb">
          <el-input  autocomplete="off"  v-model="form.rnmb"/>
        </el-form-item>
        <el-form-item label="类型"   prop="rtype" >
          <el-select v-model="form.rtype" placeholder="选择客房类型" >
            <el-option label="标准间" value="1" />
            <el-option label="大床房" value="2" />
            <el-option label="三人间" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格"   prop="price" >
          <el-input  autocomplete="off" v-model.number="form.price" />
        </el-form-item>
        <el-form-item label="封面"   prop="rpic">
            <el-input v-show="false"  autocomplete="off"  v-model="form.rpic"     />
            <el-upload
              class="avatar-uploader"
              action="http://localhost:8082/lxhotel/uploadServlet.do"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>

        </el-form-item>
        <el-form-item label="详情"   prop="rmark" >
           <!-- <el-input  autocomplete="off"  :rows="2"  v-model="form.rmark"  type="textarea" autosize/> -->
           <editor  api-key="no-api-key"   :init="setting"  v-model="form.rmark"  />
        </el-form-item>
      </el-form>



      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEdit(formRef)">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- /添加框-->

  </template>






<script >
 import {roomList,roomDelOper,roomDelsOper,roomEditOper,checkRnmbRepOper,roomFindOper,roomListPage,roomListQueryPage,exprotRoom} from '../api/room'
 import { radioGroupEmits, selectGroupKey } from 'element-plus';
 import { toRefs,reactive,ref } from 'vue'
 import tinymce from 'tinymce/tinymce'
 import Editor from '@tinymce/tinymce-vue'
 import { ElMessage } from 'element-plus'




export default{
   name:'Room',
   components:{Editor},
   setup(){
        const multipleTableRef = ref();
        const datax =  reactive( { tableData : []} )  //返回一个对象的响应式代理
        let pageObj = reactive({currentPage:1,pageSize:5,totalRow:15})
        async function loadData(){ //定义加载数据的函数
         // let rlist = await  roomList();//null
         let rData = await  roomListPage(pageObj);
          datax.tableData =  rData.list; 
          pageObj.totalRow = rData.total;
        }
        loadData();

        async function  handleDel(i){ //执行删除操作
          console.log( datax.tableData[i].roomid)
          let rcode = await roomDelOper(datax.tableData[i].roomid); //异步方法
          if(rcode == 0){
            loadData();
          }
        }

        async function  handleDels(i){ //执行多条删除操作
          const rows = multipleTableRef.value.getSelectionRows(); //获取选中的行
          const ids=[];
          rows.forEach(function(obj,el){
            ids.push("rid="+obj.roomid)
          });
          let rcode = await    roomDelsOper(ids); //异步方法
          if(rcode == 0){
            loadData(); //再次加载列表数据
          }
        }


      
         //编辑客房
        async function handleEdit(formEl){
          if (!formEl) return
          tinymce.triggerSave();//同步文本编辑器的内容
          await  formEl.validate(async function(valid){
                 
                if(valid){
                    let rcode = await   roomEditOper(form);
                    if(rcode==0){
                      formEl.resetFields(); //resetFields重置属性值
                      dialogFormVisible.value = false; //关闭弹出框
                      loadData(); //再次加载列表数据
                    }
                }else{
                    console.error("验证失败  ")
                }
          })
        }

        //更新客房信息
        async function handleUpdate(i){
            let room =  await roomFindOper(datax.tableData[i].roomid); 
            for(let key in form) { //从room 对象复制 属性值 给 form 对象
               form[key] = room[key]
            }

            imageUrl.value = form.rpic;
            dialogFormVisible.value = true;
        }



        const dialogFormVisible = ref(false) ;//定义响应式遍历，来控制弹出框的展示
        //`roomid`,`rnmb`,`rtype`,`price`,`rpic`,`rmark`,`ydstate`,`ustate`,
        let form = reactive({
          roomid:'',rnmb:'',rtype:'',price:'',rpic:'',rmark:'测试书',ydstate:'',ustate:''
        })

    
        //验证房号是否重复
        async function checkRnmbRep(r,val,callbackfn){  //callbackfn 回调函数
              let rcode = await  checkRnmbRepOper(val); //异步方法
              console.log("rcode",rcode);
              if(rcode == 1){
                return callbackfn(new Error('此房间号已经使用了')) //验证不通过
              }else{
                callbackfn() //验证通过
              }
        }
        const formRef = ref();
        const rules = reactive({
            rnmb:[
                {required: true,message:'客房编号是必须的'},
               // {validator:checkRnmbRep,trigger: 'blur'} // 自定义验证规则
            ],
            price:[
                {required: true,message:'客房价格是必须的'},
                { type: 'number', message: '价格必须是数字'}
            ],
            rtype:[
                {required: true,message:'客房类型是必须的'}
            ]
        })

        //关闭对话框调用
        function handleClose(formEl){
         if (!formEl) return
         formEl.resetFields(); //resetFields重置属性值
        }


      
        function handleCurrentChange(val){
            pageObj.currentPage = val;
            // loadData();
            loadQueryPageData();
        }
        function handleSizeChange(val){
          pageObj.pageSize = val ;
          // loadData();
          loadQueryPageData();
        }

      //条件组合查询form对象
        let queryForm = reactive({
          rnmb:'',rtype:'',price:''
        })


        async function loadQueryPageData(){ //定义按查询条件加载列表数据
         let rData = await  roomListQueryPage(queryForm,pageObj);
          datax.tableData =  rData.list; 
          pageObj.totalRow = rData.total;
        }

        function handleQuery(){//执行条件查询
                loadQueryPageData()
        }


  // 上传客房封面
        let imageUrl = ref('')   ;
        function handleAvatarSuccess(resp,uploadFile){
            console.log("文件上传成功，回调",resp);
            if(resp.code ==0){
              imageUrl.value =  resp.dataparam.imgUrl ;
              form.rpic = resp.dataparam.imgUrl;
              console.log('imageUrl',imageUrl);
            }
        }

        //图片上传前的回调函数
        function beforeAvatarUpload(){
          console.log("文件开始上传，回调");
        }


        //富文本编辑器
        const setting= {
            language_url:'/langs/zh-Hans.js',
            language: 'zh-Hans',width:'100%',
            menubar:'',promotion:false,
            plugins:'emoticons image link table code',
            toolbar:'bold italic underline strikethrough|emoticons image link table|code help' ,
            images_upload_url: 'http://localhost:8082/lxhotel/uploadServlet2.do'
        }

        //导出数据
        function handleImportRoomSuccess(resp,uploadFile){
            if(resp.code == 0){ //文件导入成功！！
              ElMessage.success(resp.msg)
            }else{//文件导入失败！！
              ElMessage.success(resp.msg)
            }
        }
       return {
          ... toRefs(datax), // ... 拆解对象，张开对象     
          handleDel,
          handleDels,
          handleEdit,
          handleUpdate,
          handleClose,
          handleCurrentChange,
          handleSizeChange,
          multipleTableRef,
          dialogFormVisible,
          form,
          formRef,
          rules,
          pageObj,
          queryForm,
          handleQuery,
          handleAvatarSuccess,
          beforeAvatarUpload,
          imageUrl,
          setting,
          handleImportRoomSuccess
       }
   }
}
 
</script>


<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.rpic{
  height: 100px;
  z-index: 1000;
}
</style>

